
var CkOK =false;
var parameter = getRequest();
var username = parameter['username'];//参数名

$(function(){

    setbillmain();
    setbilldetail();
    bindEnterEvents();  //定回车焦点移动到下一个输入文本框中

    //设置客户下拉
    $.ajax({
        url: strLin + 'contact/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#clientName').combobox({
                valueField: 'sid',
                textField: 'sname',
                data:cdata.data,
                onChange: function(param){
                    getDatakc()
                }
            });
        }
    });
//经手人
    $.ajax({
        url: strLin + 'brokerage/selectAll',
        type: 'get',
        dataType: 'json',
        success: function (cdata) {
            $('#brokerage').combobox({
                valueField: 'sid',
                textField: 'sname',
                data:cdata.data,
            });
        }
    });
});


function setbillmain() {
    $("#billmain").datagrid({
        url: '',
        queryParams: {},
        striped: true,
        fit: true,
        showFooter: true,
        idField: 'iid',
        cache: false,
        rownumbers: true,
        rownumberWidth: 50,
        checkOnSelect: false,
        selectOnCheck: false,
        singleSelect: true,
        columns: [[
            {field: 'iid', title: '序号主键', hidden: true, width: 50},/*只是不想改字段了，就是一个唯一序号，不是任何表的主键*/
            {field: 'order_detail_id', title: '订单明细主键', hidden: true, width: 50},
            {field: 'plan_id', title: '计划单主键', hidden: true, width: 50},
            {field: 'gdid', title: '缸号', halign: 'center', align: 'center', width: 70},
            {field: 'order_code', title: '订单号', halign: 'center', align: 'center', width: 120},
            {field: 'product_sid', title: '品名', halign: 'center', align: 'center', width: 200},
            {field: 'color', title: '颜色', halign: 'center', align: 'center', width: 120},
            // {field: 'color_code', title: '色号', halign: 'center', align: 'center', width: 100},
            // {field: 'color_code', title: '色块', halign: 'center', styler: colorStylerFormatter, align: 'center', width: 50},
            // {field: 'amount', title: '件数', halign: 'center', align: 'right', formatter: formatter, width: 80},
            {field: 'price', title: '单价', halign: 'center', align: 'right', width: 80},
            {field: 'kilo', title: '重量', halign: 'center', align: 'right', width: 100},
            {field: 'state', checkbox: true, width: 50}

        ]],
        onClickRow:function (index, row) {
            //在用户点击一行的时候触发
            // console.log($('#billmain').datagrid('getSelected'))
            if (judgeCK(row.iid)==false){
                $("#billgrid").edatagrid('appendRow', row);
                $('#billmain').datagrid('checkRow', index);
                compute();
                SetClient();
            }else{
                $('#billmain').datagrid('uncheckRow', index);
                setdetail(row.iid);
                compute();
                SetClient();
            }

        },
        onCheck: function (index, row) {
            //在用户勾选一行的时候触发
            SetonCheck(row);
            compute();
            SetClient();
        },
        onUncheck: function (index, row) {
            //在用户取消勾选一行的时候触发
            console.log('取消勾选')
            // $("#billgrid").edatagrid('destroyRow');
            setdetail(row.iid);
            compute();
            SetClient();

        },
        onCheckAll: function (index, row) {
            //勾选所有
            $('#billgrid').datagrid('loadData',{total:0,rows:[]})
            SetonCheckAll();
            compute();
            SetClient();
        },
        onUncheckAll: function (index, row) {
            //取消所有勾选
            $('#billgrid').datagrid('loadData',{total:0,rows:[]})
            compute()
            SetClient();
        },
    });
}

function setbilldetail() {
    $('#billgrid').edatagrid({
        // url: '../../jquery-easyui-edatagrid/datagrid_data.json',
        data: [],
        singleSelect :true,   //如果为true，则只允许选择一行
        rownumbers:true,     //显示行号
        striped: true,
        fit: true,
        // autoSave: true,
        sortable: true,
        remoteSort: false,
        showFooter: true,
        height: 'auto',
        columns: [[
            {field: 'iid', title: '主键', hidden: true, width: 50},
            {field: 'order_detail_id', title: '订单明细主键', hidden: true, width: 50},
            {field: 'plan_id', title: '计划单主键', hidden: true, width: 50},
            {field: 'gdid', title: '缸号', halign: 'center', align: 'center', width: 70},
            {field: 'order_code', title: '订单号', halign: 'center', align: 'center', width: 120},
            {field: 'product_sid', title: '品名', halign: 'center', align: 'center', width: 200},
            {field: 'color', title: '颜色', halign: 'center', align: 'center', width: 120},
            // {field: 'color_code', title: '色号', halign: 'center', align: 'center', width: 100},
            // {field: 'color_code',title: '色块', halign: 'center', styler: colorStylerFormatter, align: 'center', width: 50},
            {field: 'price', title: '单价', halign: 'center', align: 'right', width: 80, editor: {type: "textbox", options: {}}},
            {field: 'kilo', title: '重量', halign: 'center', align: 'right', width: 120, editor: {type: "textbox", options: {}}},
            {field: 'remark', title: '备注', halign: 'center', align: 'center', width: 150, editor: {type: "textbox", options: {}}},
            // {field: 'state', checkbox: true, width: 50}

        ]],
        onLoadSuccess: function (data) {
            compute();
            $(this).datagrid('resize');
            $('#setfhbill').linkbutton('disable');
        },
        onSave: function (index, row) {
            compute();
        },
        onDestroy: function (index, row) {
            compute();
        },
        onEdit: function (i, r) {
            index = i;
        },
        onSelect: function (i, d) {
            index = i;
        },
    });
}

function btn_add() {
    $('#billgrid').edatagrid('saveRow')
    let detailBill = $("#billgrid").datagrid("getRows");
    console.log(detailBill);
}

//合计
function computemain() {
    let rows = $("#billmain").edatagrid("getRows");
    let number = 0, qty = 0;
    for (let i = 0; i < rows.length; i++) {
        // number += parseFloat(rows[i].amount ? rows[i].amount : 0);
        qty += parseFloat(rows[i].kilo ? rows[i].kilo : 0);

    }
    $("#billmain").edatagrid('reloadFooter', [
        {
            product_sid: '合计',
            // amount: number.toFixed(0),
            kilo: qty.toFixed(1),
        }
    ]);
}

function compute() {
    let rows = $("#billgrid").edatagrid("getRows");
    let number = 0, qty = 0;
    for (let i = 0; i < rows.length; i++) {
        // number += parseFloat(rows[i].amount ? rows[i].amount : 0);
        qty += parseFloat(rows[i].kilo ? rows[i].kilo : 0);

    }
    $("#billgrid").edatagrid('reloadFooter', [
        {
            product_sid: '合计',
            // amount: number.toFixed(0),
            kilo: qty.toFixed(1),
        }
    ]);
}


//根据客户查询库存
function getDatakc() {

    var m_khname = $("#clientName").combobox('getText');
    var m_khid = $("#clientName").combobox('getValue');
    $.ajax({
        url: strLin + 'dynamicQuery/callProc',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(['usp_getcpDetail_kc',m_khname]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let data=cdata.data;
            console.log(data);

            $('#billmain').datagrid('loadData',data);
            // $('#billgrid').datagrid('loadData',[]);
            $('#billmain').datagrid('clearChecked');
            computemain()
            compute()
        }

    });
}

//判断row是否为空
function checkEmptyRow(data) {
    for (let i = 0; i < data.length; i++) {
        if (data[i].billtypeId) {
            return true;
        }
    }
    return false;
}

/* 清行 */
function btn_delete_line() {
    $("#billgrid").edatagrid('destroyRow');
}

/*新增行*/
function btn_add_line() {
    $('#billgrid').edatagrid('addRow');
}

/* 复制 */
function btn_copy_line() {
    $("#billgrid").edatagrid("saveRow");
    let selected = $("#billgrid").edatagrid("getSelected");
    if (selected) {
        selected = JSON.parse(JSON.stringify(selected));
        selected['pairNO'] = '';
        selected['id'] = '';
        selected['pId'] = '';
        $("#billgrid").edatagrid("addRow", {index: index + 1, row: selected});
    } else {
        $.messager.show({title: "提示", msg: "请选择原始行以复制"});
    }
};

//获取时间 getDate(0)
function getDate(param) {
    if (isNaN(param)) {
        param = 0;
    }
    var curDate = new Date();
    var newDate = new Date(curDate);
    newDate.setDate(curDate.getDate() + param);
    var year = newDate.getFullYear();
    var month = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
    var date = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate();
    var separator = '-';
    return year + separator + month + separator + date;
}


//关闭当前标签页事件
function closeTab() {
    window.parent.closeTab();
}

//字段格式化
function formatter(v, r, i) {
    if (!isNaN(v) && v) {
        return v.toFixed(1);
    } else {
        return null;
    }
}

//  颜色格式化方法
function colorStylerFormatter(v, r, i) {
    return v ? `background-color:${v};color:${v};` : null;
}

//判断是否已经勾选
function judgeCK(vID){
    var $grid = $('#billmain');
    var chkRows=$grid.datagrid('getChecked');   //获取所有被选中的行

    for (var i = 0; i < chkRows.length; i++) {
        if (vID==chkRows[i].iid){
            return  true;
            break;
        }
    }
    return false;
}

//根据勾选的情况填充编辑器
function setdetail(vID) {
    var $grid = $('#billgrid');
    var chkRows=$grid.datagrid('getRows');   //获取所有数据
    // $('#billgrid').datagrid('loadData',{total:0,rows:[]})
    for (var i = 0; i < chkRows.length; i++) {
        if (vID==chkRows[i].iid){
            $('#billgrid').datagrid('deleteRow',i)
             break;
        }
    }
    $("#billgrid").edatagrid("saveRow");
}

//设置勾选所有情况下填充
function SetonCheck(vROW) {
    var judge=false;
    var $grid = $('#billgrid');
    var chkRows=$grid.datagrid('getRows');   //获取所有数据
    for (var i = 0; i < chkRows.length; i++) {
        if (vROW.iid==chkRows[i].iid){
            // console.log('退出？');
            judge=true;
        }
    }
    if (judge==false) {
            $("#billgrid").edatagrid('appendRow', vROW);
        $("#billgrid").edatagrid("saveRow");
    }
}

//设置勾选所有情况下填充
function SetonCheckAll() {
    var $gridmain = $('#billmain');
    var billmain=$gridmain.datagrid('getRows');   //获取所有数据
    for (var i = 0; i < billmain.length; i++) {

        $("#billgrid").edatagrid("addRow", {index: i, row: billmain[i]});
        // break;

    }
    $("#billgrid").edatagrid("saveRow");

}

function SetClient() {
    let detailData=$('#billgrid').datagrid('getRows');
    if (detailData.length>0){
        $("#clientName").combobox("disable");  //不可用状态
        $('#setfhbill').linkbutton('enable');
    }else{
        $("#clientName").combobox("enable");   //恢复可用
        $('#setfhbill').linkbutton('disable');
    }
}

//生成发货单据
function setFH() {
    $("#billgrid").edatagrid("saveRow");
    var m_khname = $("#clientName").combobox('getText');
    var m_khid = $("#clientName").combobox('getValue');
    var strData=$('#billgrid').datagrid('getRows');
    var strDataNow=[];

    for (let i = 0; i < strData.length; i++) {
        strDataNow[i]={
            "order_detail_id":strData[i].order_detail_id,
            "plan_id":strData[i].plan_id,
            "order_code":strData[i].order_code,
            "goods_sid":strData[i].product_sid,
            "color":strData[i].color,
            "color_code":strData[i].color_code,
            "price":strData[i].price,
            "kilo":strData[i].kilo,
            "remark":strData[i].remark,
        }
    }

    console.log(strDataNow);
    var SQLstr = {
        "main": {
            "bill_type": '成品发货',
            "client_sid": m_khid,
            "driver": $("#driver").textbox('getValue'),
            "license_number": $("#license_number").textbox('getValue'),
            "brokerage": $("#brokerage").combobox('getText'),
            "remark": $("#remark").textbox('getValue'),
        },
        "details": strDataNow
    };
    console.log(SQLstr);

    $.ajax({
        url: strLin + 'billCp/insert',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(SQLstr),
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log('保存成功data');
            console.log(data);

            $("#driver").textbox("setValue", '');
            $("#license_number").textbox("setValue", '');
            $("#brokerage").combobox("setValue", '');
            $("#remark").textbox("setValue", '');

            $('#billmain').datagrid('clearChecked');
            getDatakc();
            // $('#billmain').datagrid('loadData',[]);
            // $('#billgrid').datagrid('loadData',[]);
            computemain();
            compute();
            SetClient();
            // getDatakc();

            setTimeout(function(){
                window.parent.addTab('成品发货-' + data.data.main.bill_code,'main/html/CPGL/cpfhbillprint.html?mainId='+data.data.main.iid+'&userName='+username);
            },1000)

        }
    });
}


